package com.glodon.springbootredission.config;

import com.glodon.springbootredission.redisson.RedissonDistributeLocker;
import com.glodon.springbootredission.util.RedissonLockUtils;
import io.reactivex.Single;
import lombok.Setter;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author zhaoxin
 * @version 1.0
 * @description: redisson bean管理
 * @date 2021/11/12 14:35
 */
@Setter
@Configuration
@ConfigurationProperties("spring.redis")
public class RedissonConfig {
    String host;
    String password;
    String port;
    int database;
    String timeout;
    @Value("${redisson.timeout}")
    int redissionTimeout;
    @Bean(destroyMethod = "shutdown")
    @Primary
    public RedissonClient createRedissonClient(){
        Config config =new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress("redis://" + host + ":" + port).setPassword(password).setDatabase(4).setTimeout(redissionTimeout);

        return Redisson.create(config);
    }

    /**
     * 哨兵模式自动装配
     * @return
     */
  /*  @Bean
    RedissonClient redissonSentinel() {
        Config config = new Config();
        SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(redssionProperties.getSentinelAddresses())
                .setMasterName(redssionProperties.getMasterName())
                .setTimeout(redssionProperties.getTimeout())
                .setMasterConnectionPoolSize(redssionProperties.getMasterConnectionPoolSize())
                .setSlaveConnectionPoolSize(redssionProperties.getSlaveConnectionPoolSize());

        if(StringUtils.isNotBlank(redssionProperties.getPassword())) {
            serverConfig.setPassword(redssionProperties.getPassword());
        }
        return Redisson.create(config);
    }*/

    /**
     * 分布式锁实例化并交给工具类
     * @param redissonClient
     */
    @Bean
    public RedissonDistributeLocker redissonLocker(RedissonClient redissonClient){
        RedissonDistributeLocker redissonDistributeLocker =new RedissonDistributeLocker(redissonClient);
        RedissonLockUtils.setLocker(redissonDistributeLocker);
        return redissonDistributeLocker;
    }
}
